<template>
	<section class="header_box">
		<el-button type="primary" class="buttom">
	        <label>导入表格</label>
	        <input class="header_importf" name="file" ref='file' type="file"  multiple="multiple" @change="importfExcel"  />
	    </el-button>
	    <el-button type="success" :disabled="disabled" @click="exportExcel('exportExcel')">
	        <a ref="exportExcel" >导出表格</a>
	    </el-button>
	    <el-button type="warning" :disabled="disabled || !hasExport" @click="batchExportExcel('batchExportExcel')">
	        <a ref="batchExportExcel" :style="{cursor:!hasExport?'not-allowed':'pointer'}">批量导出表格</a>
	    </el-button>
	    <el-link type="primary">导入表格</el-link>
	    <el-tag type="danger">{{tableNum}}</el-tag>
	    <el-link type="primary">张</el-link>

	    <!-- 导出表格样板 -->
	    <section  v-show="false">
	    	<table ref="tableBox" >
		    	<!-- 表头 -->
		    	<tr><td style="height: 50px; font-size: 16;" :colspan="Object.keys(tableHead).length">{{tableName[index]}}</td></tr>
		    	<tr>
					<th style="height: 50px; font-size: 14;" v-for="(item, index) in Object.values(tableHead).filter(v => v)" :key="index">{{item}}</th>
		    	</tr>
		    	<tr v-for="(item, index) in data.filter(v => v)" :key="index">
					<td style="height: 40px; font-size: 12;" align="center" v-for="(col, i) in Object.values(item)" :key="i">{{col}}</td>
		    	</tr>
		    </table>
	    </section>
	</section>
</template>

<script>
	export default {
		name: 'HeaderLeft',
		title: '头部左边',
		props: {
			processNum: [String, Number],			// 模板数量
			tableIndex: [String, Number],			// 表格索引
			disabled: [Boolean],					// 禁止
			tableName: [Array, Object],				// 表格名称
			tableHead: [Array, Object],      		// 表头数据
			tableData: [Array, Object],      		// 表格数据
			tableAllData: [Array, Object],      	// 表格全部数据
			originalTableData: [Array, Object],     // 表格原有数据
			originalTableHead: [Array, Object],     // 表头原有数据
			executeStep: [Function],				// 模板步骤
		},
		computed: {
			// 表格数量
			tableNum() {
				return this.tableAllData.length
			}
		},
		watch: {
			tableData() {
				this.data = this.tableData
				this.index = this.tableIndex
			}
		},
		methods: {
			// 清除无用的数据
	        uselessData(data) {
	            // 保存表头和原有表头
	            let tableHead, originalTableHead = []
	            let regNumber = /^[a-zA-Z][0-9]+$/
	            let array = data.filter((v) => {
	                let key = Object.keys(v)[0]
	                if(!regNumber.test(v[key])){
	                    tableHead = v
	                }
	                return regNumber.test(v[key])
	            })
	            this.originalTableHead.push(tableHead)
	            // 向父组件传值
                this.$emit('parentData', {
                	tableHead: tableHead,                	
                	originalTableHead: this.originalTableHead,
                })
	            return array
	        },
			// 导入表格
	        importfExcel(event) {
	        	let files = event.target.files
        		files = Array.from(files).filter((v) => v.name.indexOf('.xls') > -1 || v.name.indexOf('.xlsx') > -1 )
	        	// 初始化,向父组件传值
	        	this.hasExport = true
                this.$emit('parentData', {
                	tableName: [],
                	tableHead: [], 
                	tableData: [],      
                	tableAllData: [],         	
                	originalTableHead: [],
                	originalTableData: [],
                	tableIndex: 0,
                	rowsArray: [],
                	sortName: null,
                })
                this.$nextTick(() => {
		            // 判断是否有模板
		            if(!this.processNum && files.length > 1){
		                this.$message.error('没有选择模板请上传一张保存模板！');
		                return
		            }
		            if(!files.length){
		                return false
		            }
		            Array.from(files).forEach((file) => {
		                this.reader(file, files.length)
		            })
		            // 导入数据初始化
		            this.$refs.file.value = null
                })
	        },
	        // 转换导入数据
	        reader(file, leng) {
	            let _this = this;
	            
	            (function(name, file) {
	            	let tableData, tableAllData, tableName, originalTableData = []
	                let rABS = false; //是否将文件读取为二进制字符串
	                let reader = new FileReader();
	                if(rABS) {
	                    reader.readAsArrayBuffer(file);
	                } else {
	                    reader.readAsBinaryString(file);
	                }
	                reader.onload = function(e) {
	                    let data = e.target.result;
	                    if(rABS) {
	                        _this.readData = XLSX.read(btoa(_this.fixdata(data)), {//手动转化
	                            type: 'base64'
	                        });
	                    } else {
	                        _this.readData = XLSX.read(data, {
	                            type: 'binary'
	                        });
	                    }           
	                    //保存数据
						let array = XLSX.utils.sheet_to_json(_this.readData.Sheets[_this.readData.SheetNames[0]])
	                    // 判断导入表格与模板是否匹配
	                    if(_this.$Util.hasHintDialog.call(_this, `导入的表格与设计的不一致，表格名称是：${file.name}`, !array.length)) {
	                    	tableData = _this.uselessData(array) 
	                    	// 启动模板步骤
		                    if(_this.processNum) {
		                        tableData = _this.executeStep(tableData)
		                    }
		                    // 如果导入一张表格可以进行操作
		                    if(leng === 1){
		                    	originalTableData = _this.originalTableData	
		                    	originalTableData.push(tableData)             
		                    }
	                        // 添加名称
	                        tableName = _this.tableName
	                        tableName.push(name)
	                        tableAllData = _this.tableAllData
	                        tableAllData.push(tableData)
	                        // 展示数据
	                        tableData = _this.tableAllData[0]
	                        // 向父组件传值
	                        _this.$emit('parentData', {
	                        	tableData,							// 表格数据
	                        	tableAllData,						// 表格全部数据
	                        	tableName,							// 表名
	                        	originalTableData,					// 表格原有数据
	                        })
	                    }
	                };
	            })(file.name, file)
	        },
	        // 文件流转BinaryString
	        fixdata(data) {
	            let o = "", l = 0,     w = 10240;
	            for(; l < data.byteLength / w; ++l) {
	                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
	            }
	            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
	            return o;
	        },
	        // 导出表格
	        exportExcel(el) {
	            this.data = this.tableAllData[this.index]
	            let worksheet = this.readData.SheetNames[0];
	            // 使用延迟防止数据还没更新
	            this.$nextTick(() => {
	            	let str = this.$refs.tableBox.outerHTML
	            	this.tableToExcel(el)(str,worksheet)
	            })
	        },
	        // 批量导出
	        batchExportExcel(el) {
	            this.hasExport = true
	            let index = 0
	            this.timer = setInterval(() => { 
	           		this.index =  index          
	                if(index === this.tableNum){
	                    this.hasExport = false
	                    this.$refs[el].href = "javascript:;"
	                    this.$refs[el].download = null
	                    this.index =  index  - 1
	                    clearInterval(this.timer)
	                }else{
	                    this.exportExcel(el)
	                    this.$nextTick(() => {
	                    	//IE
		                    if(document.all) {
		                        this.$refs[el].click();
		                    }
		                    // 其它浏览器
		                    else {
		                        let e = document.createEvent("MouseEvents");
		                        e.initEvent("click", false, false);
		                        this.$refs[el].dispatchEvent(e);
		                    }		               
		                    // 向父组件传值
	                        this.$emit('parentData', {
	                        	tableIndex: index,
	                        	tableData: this.data
	                        })
	                        index++
	                    })	             
	                }
	            }, 1000)
	        },
	        // 生成模板
	        tableToExcel(el) {
	            let _this = this
	            let uri = 'data:application/vnd.ms-excel;base64,';
	            let template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
	                // 输出base64编码
	            let base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
	            let format = function(s, c) {
	                return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; })
	            }
	            return function(table, name) {
	                if (table.nodeType) table = table.innerHTML
	                let ctx = { worksheet: name || 'Worksheet', table: table }
	                _this.$refs[el].href = uri + base64(format(template, ctx));
	                _this.$refs[el].download = _this.tableName[_this.index];
	            }
	        },
		},
		data() {
			return {
				data: [],
				readData: '',							// 读取完成的数据
				hasExport: true,						// 判断是否已经导出
				index: 0,
			}
		},
		mounted() {
		}
	}
</script>
<style lang="scss" scoped>
	.header_box{
		width: 100%;
		.buttom{
			position: relative;
        	cursor: pointer;
		}
		.header_importf{
	        width: 100%;
	        height: 100%;
	        position: absolute;
	        top: 0;
	        left: 0;
	        cursor: pointer;
	        font-size: 0;
	        margin: 0;
	        padding: 0;
	        border: 0;
	        opacity: 0;
	    }
	}
</style>